package com.wzq.solution;

import com.wzq.solution.node.TreeNode;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

class Solution102 {
    /*public List<List<Integer>> levelOrder(TreeNode root) {
        List<List<Integer>> rst = new ArrayList<List<Integer>>();
        levelOrder2(root,0,rst);
        return rst;
    }
    
    public void levelOrder2(TreeNode root,int level,List<List<Integer>> rst) {
        if(root == null){
            return;
        }

        if(rst.size()<= level){
            rst.set(level,new ArrayList<Integer>());
        }
        rst.get(level).add(root.val);
        levelOrder2(root.left,level+1,rst);
        levelOrder2(root.right,level+1,rst);
        
    }*/


    public List<List<Integer>> levelOrder(TreeNode root) {
        LinkedList<List<Integer>> rst = new LinkedList<List<Integer>>();
        Queue<TreeNode> queue = new LinkedList<TreeNode>();
        queue.add(root);
        while (!queue.isEmpty()){
            int count = queue.size();
            List<Integer> levelRst = new ArrayList<Integer>();
            while (count-->0){
                TreeNode node = queue.poll();

                if (node.left != null){
                    queue.add(node.left);
                }
                if (node.right != null){
                    queue.add(node.right);
                }

                levelRst.add(node.val);
            }
            rst.addFirst(levelRst);
        }
        return rst;
    }

}